<template>
  <div class="app-container">
    <el-table v-loading="loading" :data="oddjobList">
      <el-table-column type="index" width="55" align="center" />
      <el-table-column label="出工方式" align="center" prop="wm.wmName" />
      <el-table-column label="车间" align="center" prop="slWorkshop.workshopName" />
      <el-table-column label="大工序" align="center" prop="slGprocess.gprocessName" />
      <el-table-column label="开始时间" align="center" prop="oddjobStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.oddjobStart, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="oddjobEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.oddjobEnd, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="oddjobDuration" />
      <el-table-column label="计薪" align="center" prop="wmPay" >
        <template slot-scope="scope">
          <span>{{ scope.row.wmPay}} 元/{{ sourceWmUnitFormat(scope.row.wmUnit) }} </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['sl:oddjob:edit']"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详细零工报工对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出工方式" prop="wmId">
              {{ form.wm != null ? form.wm.wmName : '' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计薪" prop="wmPay">
                {{ form.wmPay }} 元/{{ sourceWmUnitFormat(form.wmUnit) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="oddjobStart">
              {{form.oddjobStart}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="oddjobEnd">
              {{form.oddjobEnd}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
           <el-form-item label="时长" prop="oddjobDuration">
             {{form.oddjobDuration}}
           </el-form-item>
          </el-col>
       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="所属模块" prop="moduleId">
             {{ form.slModule != null ? form.slModule.moduleName : '' }}
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="所属车间" prop="workshopId">
              {{ form.slWorkshop != null ? form.slWorkshop.workshopName : '' }}
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="大工序" prop="gprocessId">
             {{ form.slGprocess != null ? form.slGprocess.gprocessName : '' }}
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="小工序" prop="processId">
             {{ form.slProcess != null ? form.slProcess.processName : '' }}
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="实际生产" prop="oddjobActual">
             {{form.oddjobActual}}
           </el-form-item>
         </el-col>
       </el-row>
        <el-divider content-position="center">零工操作人信息</el-divider>
        <el-table :data="slOddjobOmemberList" :row-class-name="rowSlOddjobOmemberIndex" ref="slOddjobOmember" style="width:100%">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="操作人" prop="omemberNick" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="this.$store.state.user.name===form.oddjobUser" type="primary" @click="handleUpdate">修改报工</el-button>
        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改零工报工对话框 -->
     <el-dialog :title="editTitle" :visible.sync="editOpen" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出工方式" prop="wmId">
              <el-select v-model="form.wmId"  @change="handleGetwmPay" placeholder="请选择">
                <el-option
                  v-for="item in wmOptions"
                  :key="item.wmId"
                  :label="item.wmName"
                  :value="item.wmId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计薪" prop="wmPay">
              <el-input v-model="form.wmPay" :disabled="true" placeholder="请输入计薪" >
                <template slot="append">元/{{ sourceWmUnitFormat(form.wmUnit) }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="oddjobStart">
              <el-date-picker clearable
                v-model="form.oddjobStart"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                default-time="12:00:00"
                placeholder="请选择开始时间"
                @change="handleCompareTime"
                >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="oddjobEnd">
              <el-date-picker clearable
                v-model="form.oddjobEnd"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间"
                @change="handleCompareTime"
                >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
           <el-form-item label="时长" prop="oddjobDuration">
             <el-input v-model="form.oddjobDuration"  class="def-input-number" type="number" placeholder="请输入时长" />
           </el-form-item>
          </el-col>
       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="所属模块" prop="moduleId">
             <el-select v-model="form.moduleId" :disabled="true" filterable @change="handleChangeModule" placeholder="请选择所属模块">
               <el-option v-for="item in moduleOptions" :key="item.moduleId" :label="item.moduleName"
                 :value="item.moduleId" :disabled="item.status == 1"></el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="所属车间" prop="workshopId">
             <el-select v-model="form.workshopId" filterable @change="handleChangeWorkshop" placeholder="请选择所属车间">
               <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                 :value="item.workshopId" :disabled="item.status == 1"></el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="大工序" prop="gprocessId">
             <el-select v-model="form.gprocessId" filterable @change="handleChangeProcess" placeholder="请选择大工序">
               <el-option v-for="item in gprocessOptions" :key="item.gprocessId" :label="item.gprocessName"
                 :value="item.gprocessId" :disabled="item.status == 1"></el-option>
             </el-select>
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="小工序" prop="processId">
             <el-select v-model="form.processId" filterable placeholder="请选择小工序">
               <el-option v-for="item in processOptions" :key="item.processId" :label="item.processName"
                 :value="item.processId" :disabled="item.status == 1"></el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="实际生产" prop="oddjobActual">
             <el-input v-model="form.oddjobActual"  class="def-input-number" type="number"
               placeholder="请输入实际生产" />
           </el-form-item>
         </el-col>
       </el-row>
        <el-divider content-position="center">零工操作人信息</el-divider>
<!--        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSlOddjobOmember">添加</el-button>
          </el-col>
          <UserMultiSelect ref="userSelect" @onSelected="userSelected"></UserMultiSelect>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSlOddjobOmember">删除</el-button>
          </el-col>
        </el-row> -->
        <el-table :data="slOddjobOmemberList" :row-class-name="rowSlOddjobOmemberIndex" @selection-change="handleSlOddjobOmemberSelectionChange" ref="slOddjobOmember" style="width:100%">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="操作人" prop="omemberNick" />
          <el-table-column label="职级" prop="levelName" />
          <el-table-column label="计薪方式" prop="ssmName" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="this.$store.state.user.name===form.oddjobUser" type="primary" @click="submitForm">重新提交审核</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listHOddjob,listNoSubmitOddjob,listOddjob, getOddjob, delOddjob, addOddjob, updateOddjob,updateOddjobDateTime,getOddjobOptions,isUniqueJobUser,submitDateOddjobs } from "@/api/sl/oddjob";
import UserMultiSelect from "@/components/userSelect/multi.vue"
import {getWorkshopListByModuleId} from "@/api/sl/workshop";
import {getGprocessListByWorkshopId} from "@/api/sl/gprocess";
import {getProcessListByGprocessId} from "@/api/sl/process";

export default {
  name: "Oddjob",
  components: {UserMultiSelect},
  dicts: ['sl_rwork_class','sl_wm_unit'],
  data() {
    let watermarkContentVaild = (rule, value, callback) => {
      if (value == null || value === "") {
        callback();
      } else {
        let length = value.length
        if (length > 7) {
          callback(new Error("输入不能超过7位"))
        } else {
          callback();
        }
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSlOddjobOmember: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 零工报工表格数据
      oddjobList: [],
      // 零工操作人表格数据
      slOddjobOmemberList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rfworkId: null,
        memberUser:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
         oddjobDuration: [
           {validator: watermarkContentVaild, trigger: 'blur'}
         ],
         wmPay: [
           { required: true, message: "计薪不能为空", trigger: "blur" }
         ],
         wmId: [
           { required: true, message: "出工方式工不能为空", trigger: "blur" },
         ],
         oddjobActual: [
           {validator: watermarkContentVaild, trigger: 'blur'}
         ],
      },
      moduleOptions:[],
      workshopOptions: [],
      gprocessOptions: [],
      processOptions: [],
      wmOptions:[],
      editTitle: "",
      editOpen: false
    };
  },
  created() {
    const rfworkId = this.$route.query && this.$route.query.rfworkId;
    const memberUser = this.$route.query && this.$route.query.memberUser;
    if (rfworkId) {
      this.queryParams.rfworkId = rfworkId;
    }
    if(memberUser){
      this.queryParams.memberUser = memberUser;
    }
    this.getList();

  },
  methods: {
    /** 查询零工报工列表 */
    getList() {
      this.loading = true;
      listHOddjob(this.queryParams).then(response => {
        this.oddjobList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelEdit() {
      this.editOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        oddjobId: null,
        oddjobDate: null,
        moduleId: null,
        oddjobYear: null,
        oddjobMonth: null,
        oddjobDay: null,
        isApproved: null,
        leaderUser: null,
        oddjobStart: null,
        oddjobEnd: null,
        oddjobDuration: null,
        wmPay: null,
        estimatePay: null,
        oddjobUser: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        wmId: null,
        oddjobBz: null,
        wmUnit: null,
        rfworkId: null,
        oddjobDm: null,
        workshopId: null,
        gprocessId: null,
        processId: null,
        oddjobActual: null
      };
      this.slOddjobOmemberList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.queryParams.pageNum = 1;
          this.getList();
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.oddjobId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 详细按钮操作 */
    handleDetail(row) {
      this.reset();
      const oddjobId = row.oddjobId || this.ids
      getOddjob(oddjobId).then(response => {
        this.form = response.data;
        this.wmOptions = response.wms;
        this.moduleOptions = response.modules;
        this.gprocessOptions = response.gprocesss;
        this.processOptions = response.processs;
        this.workshopOptions = response.workshops;
        this.slOddjobOmemberList = response.data.slOddjobOmemberList;
        this.open = true;
        this.title = "修改零工报工";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = false;
      this.editOpen = true;
      this.editTitle = "修改零工报工";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
         this.form.slOddjobOmemberList = this.slOddjobOmemberList;
          if (this.form.oddjobId != null) {
            updateOddjob(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const oddjobIds = row.oddjobId || this.ids;
      this.$modal.confirm('是否确认删除零工报工编号为"' + oddjobIds + '"的数据项？').then(function() {
        return delOddjob(oddjobIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 零工操作人序号 */
    rowSlOddjobOmemberIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 零工操作人添加按钮操作 */
    handleAddSlOddjobOmember() {
      this.$refs.userSelect.showFlag = true;

    },
    /** 零工操作人删除按钮操作 */
    handleDeleteSlOddjobOmember() {
      if (this.checkedSlOddjobOmember.length == 0) {
        this.$modal.msgError("请先选择要删除的零工操作人数据");
      } else {
        const slOddjobOmemberList = this.slOddjobOmemberList;
        const checkedSlOddjobOmember = this.checkedSlOddjobOmember;
        this.slOddjobOmemberList = slOddjobOmemberList.filter(function(item) {
          return checkedSlOddjobOmember.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSlOddjobOmemberSelectionChange(selection) {
      this.checkedSlOddjobOmember = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sl/oddjob/export', {
        ...this.queryParams
      }, `oddjob_${new Date().getTime()}.xlsx`)
    },
    // 计价单位字典翻译
    sourceWmUnitFormat(unit) {
      if(unit != null ){
        return this.selectDictLabel(this.dict.type.sl_wm_unit, unit);
      }
    },
    //获取出工方式计价
    handleGetwmPay(value){
      for (let i = 0; i < this.wmOptions.length; i++) {
        if (this.wmOptions[i].wmId === value) {
          this.form.wmPay = this.wmOptions[i].wmPay;
          this.form.wmUnit = this.wmOptions[i].wmUnit;
          //this.handleCountPay()
          break;
        }
      }
    },
    //比较时间
    handleCompareTime(){
      if (this.form.oddjobStart && this.form.oddjobEnd) {
        let difference = new Date(this.form.oddjobEnd) - new Date(this.form.oddjobStart);
        this.form.oddjobDuration = (difference / 3600000).toFixed(2)
        //this.handleCountPay()
      } else {
        this.form.oddjobDuration = null;
      }
    },
    //模块变更查询车间
    handleChangeModule(value) {
      //清空车间
      this.form.workshopId = null;
      this.workshopOptions = [];
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getWorkshopListByModuleId(value).then(response => {
        this.workshopOptions = response.data;
      });
    },
    //车间变更查询大工序
    handleChangeWorkshop(value) {
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getGprocessListByWorkshopId(value).then(response => {
        this.gprocessOptions = response.data;
      });
    },
    //大工序变更查询小工序
    handleChangeProcess(value) {
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getProcessListByGprocessId(value).then(response => {
        this.processOptions = response.data;
      });
    },
    userSelected(rows){
      if(rows !=null){
        rows.forEach(user => {
          let obj = {};
          obj.omemberUser = user.userName;
          obj.omemberNick = user.nickName;
          obj.levelId = user.levelId;
          obj.ssmId = user.ssmId;
          obj.levelName = user.level.levelName;
          obj.ssmName = user.ssm.ssmName;

          if(isUniqueJobUser(this.slOddjobOmemberList,obj)){
            this.slOddjobOmemberList.push(obj);
          }
        })
      }
    },
  }
};
</script>
<style>
.el-table .el-table__body-wrapper::-webkit-scrollbar {
    height: 10px;
}
</style>

